package cn.client.ui.view.signUp

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.client.data.remoteData.bean.BaseResp
import cn.client.data.remoteData.bean.PushSignUpInfo
import cn.client.data.remoteData.bean.User
import cn.client.data.remoteData.bean.VerifyAccount
import cn.client.data.remoteData.repository.SignUpRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject


/**
 * 注册ViewModel
 */
@HiltViewModel
class SignUpViewModel @Inject constructor(
    private val repository: SignUpRepository
):ViewModel() {

    /**
     * 事件管道
     */
    private val _pageEvents = Channel<PageEvent>(Channel.BUFFERED)

    /**
     * 可观察事件数据流
     */
    val pageEvents = _pageEvents.receiveAsFlow()

    /**
     * 可变状态
     */
    var pageStates by mutableStateOf(PageState())
        private set


    /**
     * 收集意图
     */
    fun dispatch(intent: PageIntent){
        when(intent) {
            is PageIntent.VerifyAccount -> verifyAccount(intent.account)
            is PageIntent.VerifyCode -> verifyCode(intent.email, intent.code)
            is PageIntent.VerifyPwd -> verifyPwd(intent.account, intent.password)
            else -> {Unit}
        }
    }


    /**
     * 注册第一步
     */
    private fun verifyAccount(account: String) {
        pageStates = pageStates.copy(account = account)
        Log.d("处理意图","输入的账号为：${pageStates.account}")
        viewModelScope.launch {
            try {
                val res = repository.signUpFirst(VerifyAccount(account))
                pageStates = pageStates.copy(verifyStatus = res.msg)
                if (res.code == 200){
                    _pageEvents.send(PageEvent.FirstRes(res))
                } else {
                    _pageEvents.send(PageEvent.Error("账户 $account 不存在，返回信息：${res.msg}"))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("error","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    /**
     * 注册第二步
     */
    private fun verifyCode(email: String, code: Int) {
        pageStates = pageStates.copy(verifyCode = code)
        val pushInfo: PushSignUpInfo = PushSignUpInfo(code = code, email = email)
        viewModelScope.launch {
            try {
                val res = repository.signUpThird(pushInfo)
                pageStates = pageStates.copy(verifyStatus = res.msg)
                if (res.code == 200){
                    _pageEvents.send(PageEvent.SecondRes(res))
                } else {
                    _pageEvents.send(PageEvent.Error("返回信息：${res.msg}"))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("error","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }

    /**
     * 注册第三步
     */
    private fun verifyPwd(account: String, password: String) {
        pageStates = pageStates.copy(password = password)
        val user: User = User(account = account, password = password)
        viewModelScope.launch {
            try {
                val res = repository.signUpSecond(user)
                pageStates = pageStates.copy(verifyStatus = res.msg)
                if (res.code == 200){
                    _pageEvents.send(PageEvent.ThirdRes(res))
                } else {
                    _pageEvents.send(PageEvent.Error("返回信息：${res.msg}"))
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("error","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }


    /**
     * 意图集
     */
    sealed class PageIntent {
        data class VerifyAccount(val account: String): PageIntent()
        data class VerifyCode(val email: String, val code: Int): PageIntent()
        data class VerifyPwd(val account: String, val password: String): PageIntent()
    }


    /**
     * 事件集
     */
    sealed class PageEvent {
        object Idle : PageEvent() // 空闲
        object Loading : PageEvent()  // 加载
        data class FirstRes(val res: BaseResp<Any>): PageEvent()
        data class SecondRes(val res: BaseResp<Any>): PageEvent()
        data class ThirdRes(val res: BaseResp<Any>): PageEvent()
        data class Error(val error: String) : PageEvent()   // 错误信息
    }




    /**
     * 状态集
     */
    data class PageState(
        val account: String = "",
        val password: String = "",
        // 验证码
        val verifyCode: Int = 0,
        // 验证状态
        val verifyStatus: String = "",
    )
}